<?php
// +----------------------------------------------------------------------
// | [KyPHP System] Copyright (c) 2020 http://www.kuryun.com/
// +----------------------------------------------------------------------
// | [KyPHP] 并不是自由软件,你可免费使用,未经许可不能去掉KyPHP相关版权
// +----------------------------------------------------------------------
// | License  https://gitee.com/fudaoji/KyPHP/blob/master/LICENSE
// +----------------------------------------------------------------------
/**
 * Created by PhpStorm.
 * Script Name: Showwxa.php
 * Create: 2020/11/17 11:31
 * Description: 扫码关注组件
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\mini\controller;

use ky\MiniPlatform\ErrorMsg;
use ky\MiniPlatform\Request\WxaGetShowWxaItem;
use ky\MiniPlatform\Request\WxaGetWxaMpLinkForShow;
use ky\MiniPlatform\Request\WxaUpdateShowWxaItem;

class Showwxa extends Base
{
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 设置扫码关注组件
     * @return mixed
     * @throws \Exception
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function index(){
        $request = new WxaGetShowWxaItem();
        $response = $this->getClient()->execute($request, $this->getAccessToken());
        $data = [];
        if($response['errcode'] == 0){
            $data = [
                "can_open" => $response['can_open'],
                "is_open" => $response['is_open']
            ];
            if($data['is_open']){
                $data = array_merge($data, [
                    "appid" => $response['appid'],
                    "nickname" => $response['nickname'],
                    "headimgurl" => $response['headimg']
                ]);
            }
        }

        $request = new WxaGetWxaMpLinkForShow();
        $request->setPage(0);
        $request->setNum(20);
        $response = $this->getClient()->execute($request, $this->getAccessToken());
        if($response['errcode'] == 0){
            $list = $response['biz_info_list'];
        }else{
            $list = [];
        }
        $this->assign['data'] = $data;
        $this->assign['data_list'] = $list;
        return $this->show();
    }

    /**
     * 设置
     * @throws \Exception
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function updatePost(){
        if(request()->isPost()){
            $post_data = input('post.');
            $request = new WxaUpdateShowWxaItem();
            $request->setAppId($post_data['appid']);
            $request->setWxaSubscribeBizFlag($post_data['flag']);
            $response = $this->getClient()->execute($request, $this->getAccessToken());
            if($response['errcode'] == 0){
                $this->success('操作成功', url('index'));
            }else{
                $this->error(ErrorMsg::getErrorMsg($response['errcode']));
            }
        }
    }
}